import {guid} from '@/utils';
import $ from 'jquery';
import {stop} from '@/components/hhd/design/DesignTable/TableHelper';
import './font/iconfont.css';

export class ContextMenu {
  menus = [];
  body = undefined;

  constructor(menus, {top, left}) {
    this.menus = menus || [];
    this.resolveUUID();
    this.createContextMenu();
    this.setPosition(top, left);
    this.bindClose();
  }

  createContextMenu() {
    this.createBodyElement();
    this.createItems();
  }

  createItems() {
    let list = this.menus
    .map(item => this.createItemByType(item))
    .filter(i => !!i)
    .forEach(i => this.body.append(i));
  }

  createItemByType(item) {
    if (item.type === 'divider') {
      return this.createDivider();
    }
    if (!item.type || item.type === 'menu') {
      return this.createItem(item);
    }
  }

  createDivider() {
    let div = document.createElement('div');
    div.className = 'divider';
    return div;
  }

  createItem(item) {
    let div = document.createElement('div');
    div.className = 'menu-item';
    div.append(this.createItemIcon(item));
    div.append(this.createItemTitle(item));
    div.addEventListener('click', e => {
      item.click && item.click(() => this.close());
    });
    return div;
  }

  createItemTitle(item) {
    let div = document.createElement('div');
    div.className = 'title';
    div.innerHTML = item.title;
    return div;
  }

  createItemIcon(item) {
    let div = document.createElement('div');
    div.className = 'icon';
    let span = document.createElement('span');
    span.className = 'iconfont';
    span.innerHTML = item.icon;
    div.append(span);
    return div;
  }

  bindClose() {
    let that = this;

    function mousedown(e) {
      let target = e.target;
      while (target && !$(target).hasClass('t-context-menu'))
        target = target.parentNode;
      if (target) return;
      window.removeEventListener('click', mousedown);
      that.close();
    }

    window.addEventListener('mousedown', mousedown);
  }

  close() {
    this.body.remove();
  }

  createBodyElement() {
    this.body = document.createElement('div');
    this.body.className = 't-context-menu';
    document.body.append(this.body);

    $(this.body).on('mousedown', stop);
    $(this.body).on('click', stop);
  }

  setPosition(top, left) {
    if (top + this.body.offsetHeight > window.innerHeight) {
      top = window.innerHeight - this.body.offsetHeight - 10
    }
    this.body.style.top = `${top}px`;
    this.body.style.left = `${left}px`;
  }

  resolveUUID() {
    this.menus.forEach(menu => {
      menu._key = menu._key || guid();
    });
  }
}